<!-- @license MIT -->

<!-- This code can execute several ScadaBR scripts sequentially -->

<input
    type="button"
    value="Run multiple scripts"
    onclick="runScripts([ 'SC_002200', 'SC_110022', 'SC_002211' ]);"
>

<div style="max-width: 50px; max-height: 50px; overflow: hidden;">
    <script>
        function runScripts(scripts) {
            if (typeof scripts == "string")
                mango.view.executeScript(scripts);
            else if (Array.isArray(scripts))
                scriptRunner(scripts, 0, 0);
        }

        function scriptRunner(scriptArray, index, retries) {
            var maxRetries = 2;

            ViewDwr.executeScript(scriptArray[index], function(success) {
                var maxIndex = scriptArray.length - 1;

                if (success && index < maxIndex) {
                    scriptRunner(scriptArray, (index + 1), 0);
                } else if (!success) {
                    if (retries < maxRetries) {
                        console.warn("Failed to run script " + scriptArray[index] + ", retrying...");
                        scriptRunner(scriptArray, index, (retries + 1));
                    } else if (index < maxIndex) {
                        scriptRunner(scriptArray, (index + 1), 0);
                    }
                }
            });
        }
    </script>
</div>
